﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/5/29 11:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 时序管理窗体
    /// </summary>
    public partial class FormTimeLine : HWFrmWithTitle
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormTimeLine()
        {
            InitializeComponent();
        }
        private void FormTimeLine_Load(object sender, EventArgs e)
        {
            InitColumns();
            LoadTimeLines();
        }
        private void InitColumns()
        {
            CommonHelper.CreateTextGridColumn(this.dataGridViewTimeLines, "Code", "工位");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTimeLines, "Name", "名称");
            CommonHelper.CreateTextGridColumn(this.dataGridViewTimeLines, "Address", "PLC地址");
            this.dataGridViewTimeLines.DoubleBufferedDataGirdView(true);
            this.dataGridViewTimeLines.InitStyle();
        }
        private void dataGridViewTcp_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
        {
        }
        private void dataGridViewTcp_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
        }
        private void LoadTimeLines()
        {
            var timelines = TimeLine.Instance().DeviceTimeLines;
            this.dataGridViewTimeLines.Rows.Clear();
            foreach (var t in timelines)
            {
                int rowIndex = this.dataGridViewTimeLines.Rows.Add(1);
                var row = this.dataGridViewTimeLines.Rows[rowIndex];
                row.Cells["Code"].Value = t.TimeLineCode;
                row.Cells["Name"].Value = t.TimeLineName;
                row.Cells["Address"].Value = t.TimeLinePLCAddress;
                row.Tag = t;
            }
        }
        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            new FormTimeLineEdit(null).ShowDialog();
            LoadTimeLines();
        }
        private void toolStripMenuItemEdit_Click(object sender, EventArgs e)
        {
            var selectedCells = this.dataGridViewTimeLines.SelectedCells;
            if (selectedCells != null && selectedCells.Count > 0)
            {
                var row = this.dataGridViewTimeLines.Rows[selectedCells[0].RowIndex];
                var timeline = (DeviceTimeLine)row.Tag;
                new FormTimeLineEdit(timeline).ShowDialog();
                LoadTimeLines();
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录再进行操作");
            }
        }
        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            var selectedCells = this.dataGridViewTimeLines.SelectedCells;
            if (selectedCells != null && selectedCells.Count > 0)
            {
                if (HWMessageBox.ShowYesNo(this, "确认删除该记录吗？") == DialogResult.Yes)
                {
                    var row = this.dataGridViewTimeLines.Rows[selectedCells[0].RowIndex];
                    var timeline = (DeviceTimeLine)row.Tag;
                    if (TimeLine.Instance().DeviceTimeLines.Remove(timeline))
                    {
                        HWMessageBox.Show(this, "删除成功");
                    }
                    else
                    {
                        HWMessageBox.Show(this, "删除失败");
                    }
                    LoadTimeLines();
                }
            }
            else
            {
                HWMessageBox.Show(this, "请先选中记录再进行操作");
            }
        }
        private void dataGridViewUsers_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex != -1)
            {
                var row = this.dataGridViewTimeLines.Rows[e.RowIndex];
                var timeline = (DeviceTimeLine)row.Tag;

                new FormTimeLineEdit(timeline).ShowDialog();
                LoadTimeLines();
            }
        }
        private void FormTimeLine_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
        private void buttonImport_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*.xlsx|*.xlsx";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                CommonHelper.ShowWaiting(this, "正在导入数据，请稍候......");
                string filePath = openFileDialog.FileName;
                List<DeviceTimeLine> timeLines = CommonHelper.ReadExcel<DeviceTimeLine>(filePath, (message) => { CommonHelper.ShowWaiting(this, message); });
                if (timeLines != null && timeLines.Count > 0)
                {
                    timeLines.RemoveAll(v => string.IsNullOrWhiteSpace(v.TimeLinePLCAddress) || string.IsNullOrWhiteSpace(v.TimeLineCode) || string.IsNullOrWhiteSpace(v.TimeLineName));
                    TimeLine.Instance().DeviceTimeLines = timeLines;
                    TimeLine.Instance().Save();
                    LoadTimeLines();
                    HWMessageBox.Show(this, "导入成功");
                }
                else
                {
                    HWMessageBox.Show(this, "没有合适的数据");
                }
            }
            CommonHelper.CloseWaiting();
        }
        private void buttonOutput_Click(object sender, EventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xlsx|*.xlsx";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                CommonHelper.ShowWaiting(this, "正在导出数据，请稍候......");
                try
                {
                    bool outputResult = CommonHelper.WriteExcel(dialog.FileName, TimeLine.Instance().DeviceTimeLines, true,
                        "时序设置", (message) => { CommonHelper.ShowWaiting(this, message); }, true, true,
                        new string[] { "TimeLineValue" });
                    if (outputResult)
                    {
                        HWMessageBox.Show(this, "导出成功");
                        CommonHelper.OpenExcelFile(dialog.FileName);
                    }
                }
                catch (Exception ex)
                {
                    HWMessageBox.Show(this, ex.Message);
                    LogHelper.Error(ex);
                }
            }
            CommonHelper.CloseWaiting();
        }
    }
}
